// 初始化数据库
let db;
const request = indexedDB.open('StorageMapDB', 1);

request.onupgradeneeded = (event) => {
  db = event.target.result;
  db.createObjectStore('items', { keyPath: 'id', autoIncrement: true });
};

request.onsuccess = (event) => {
  db = event.target.result;
  loadItems(); // 页面加载时读取数据
};

// 添加物品
document.getElementById('addBtn').addEventListener('click', () => {
  document.getElementById('cameraInput').click();
});

document.getElementById('cameraInput').addEventListener('change', async (e) => {
  const file = e.target.files[0];
  const desc = prompt('输入物品描述和位置（如"护照在书房抽屉"）：');
  if (!desc) return;

  const item = {
    desc: desc,
    time: new Date().toLocaleString(),
    image: await readFileAsDataURL(file) // 将图片转为Base64存储
  };

  const transaction = db.transaction('items', 'readwrite');
  transaction.objectStore('items').add(item);
  transaction.oncomplete = () => loadItems();
});

// 读取所有物品
function loadItems(filter = '') {
  const transaction = db.transaction('items', 'readonly');
  const request = transaction.objectStore('items').getAll();

  request.onsuccess = () => {
    const items = filter ? 
      request.result.filter(item => item.desc.includes(filter)) : 
      request.result;
    renderItems(items);
  };
}

// 搜索功能
document.getElementById('searchInput').addEventListener('input', (e) => {
  loadItems(e.target.value);
});

// 渲染物品列表
function renderItems(items) {
  const listEl = document.getElementById('itemList');
  listEl.innerHTML = items.map(item => `
    <div class="item">
      <img src="${item.image}" style="max-height: 150px;">
      <p><strong>描述：</strong>${item.desc}</p>
      <p><strong>时间：</strong>${item.time}</p>
      <button onclick="deleteItem(${item.id})">删除</button>
    </div>
  `).join('');
}

// 删除物品
window.deleteItem = (id) => {
  if (!confirm('确定删除吗？')) return;
  const transaction = db.transaction('items', 'readwrite');
  transaction.objectStore('items').delete(id);
  transaction.oncomplete = () => loadItems();
};

// 图片转Base64
function readFileAsDataURL(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target.result);
    reader.readAsDataURL(file);
  });
}